package cn.com.ylpw.web.customer.controller;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.ylpw.entity.Success;
import cn.com.ylpw.exception.CheckException;
import cn.com.ylpw.spring.SpringController;
import cn.com.ylpw.utils.StringUtils;
import cn.com.ylpw.web.order.service.IAddressService;
import cn.com.ylpw.web.util.RegexUtils;
import cn.com.ylpw.web.util.ServletUtil;
/**
 * 客户收货地址
 * 
 * @author July july_sky@foxmail.com
 * @date 2015年10月23日下午1:14:36
 * @Copyright ©2003-2015 北京春秋永乐文化传播有限公司. All Rights Reserved.
 * @version 1.0
 */
@Controller("addressCustomerController")
public class AddressCustomerController extends SpringController{
	public final Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	@Qualifier("addressService")
	private IAddressService addressService;
	@RequestMapping("/{path}/editCustomerAddr")
	public String edit(@RequestParam Map<String,Object> params,Model model,@PathVariable("path") String path,HttpSession session){
		Map<String,Object> customer = ServletUtil.getCustomer(session);
		if(StringUtils.isEmpty(customer)){
			model.addAttribute("error", "请登录后操作");
			return "errorMsg";
		}
		if(StringUtils.isBlank(params.get("addressIdCustomersId"))){
			model.addAttribute("error", "请选择要修改的地址");
			return "errorMsg";
		}
		params.put("addressIdCustomersId",Integer.valueOf(params.get("addressIdCustomersId").toString()));
		params.put("customersId", ServletUtil.getCustomerId(session));
		try {
			Map<String,Object> addr = addressService.findAddressCustomerById(params);
			if(StringUtils.isEmpty(addr)){
				model.addAttribute("error", "修改的地址不存在或错误的地址信息");
				return "errorMsg";
			}
			model.addAllAttributes(params);
			model.addAttribute("addr",addr);
			model.addAttribute("provinceList", addressService.findAllProvinces(params));
			return "/"+path+"/editCustomerAddr";
		} catch (Exception e) {
			log.warn("数据初始化异常，请稍后重试", e);
			model.addAttribute("error", "数据初始化异常，请稍后重试");
			return "errorMsg";
		}
		
	}
	@RequestMapping("/{path}/addCustomerAddr")
	public String add(@RequestParam Map<String,Object> params,Model model,@PathVariable("path") String path,HttpSession session){
		Map<String,Object> customer = ServletUtil.getCustomer(session);
		if(StringUtils.isEmpty(customer)){
			model.addAttribute("error", "请登录后操作");
			return "errorMsg";
		}
		try {
			model.addAllAttributes(params);
			model.addAttribute("provinceList", addressService.findAllProvinces(params));
			return "/"+path+"/addCustomerAddr";
		} catch (Exception e) {
			log.warn("数据初始化异常，请稍后重试", e);
			model.addAttribute("error", "数据初始化异常，请稍后重试");
			return "errorMsg";
		}
		
	}
	/**
	 * 创建新地址
	 * 
	 * @author July july_sky@foxmail.com
	 * @date 2015年10月23日下午3:08:40
	 * @param params
	 * @return
	 */
	@RequestMapping("/customerAddr/create")
	@ResponseBody
	public Success create(@RequestParam Map<String,Object> params,HttpSession session) {
		try {
			check(params,session);
			if(addressService.saveCustomerAddr(params) > 0){
				return Success.getInstance(true, "200", "保存成功");
			}
			return Success.getInstance(true, "500", "保存失败");
		} catch (CheckException e) {
			log.error("新增地址数据验证异常{}",params, e);
			return e.getSuccess();
		}catch (Exception e) {
			log.error("新增地址系统异常，请稍后重试{}",params,e);
			return Success.getInstance(false, "500", "系统异常，请稍后重试");
		}
	}
	
	/**
	 * 更新地址
	 * 
	 * @author July july_sky@foxmail.com
	 * @date 2015年10月23日下午3:08:40
	 * @param params
	 * @return
	 */
	@RequestMapping("/customerAddr/update")
	@ResponseBody
	public Success update(@RequestParam Map<String,Object> params,HttpSession session) {
		try {
			if(StringUtils.isBlank(params.get("addressIdCustomersId"))){
				return Success.getInstance(true, "500", "请选择要修改的地址");
			}
			params.put("addressIdCustomersId", Integer.valueOf(params.get("addressIdCustomersId").toString()));
			check(params,session);
			if(addressService.updateCustomerAddr(params) > 0){
				return Success.getInstance(true, "200", "保存成功");
			}
			return Success.getInstance(true, "500", "该地址不属于您，不能修改");
		} catch (CheckException e) {
			log.error("修改地址数据验证异常{}",params, e);
			return e.getSuccess();
		}catch (Exception e) {
			log.error("修改地址系统异常，请稍后重试{}",params,e);
			return Success.getInstance(false, "500", "系统异常，请稍后重试");
		}
	}
	
	/**
	 * 参数验证
	 * 
	 * @author July july_sky@foxmail.com
	 * @date 2015年10月23日下午3:08:32
	 * @param params
	 */
	private void check(Map<String,Object> params,HttpSession session){
		Integer customersId = ServletUtil.getCustomerId(session);
		if(customersId == null){
			throw new CheckException(Success.getInstance(false, "500", "请登录后操作"));
		}
		params.put("customersId", customersId);
		if(StringUtils.isBlank(params.get("provinceId")) || "cityId".equals(String.valueOf(params.get("provinceId")))){
			throw new CheckException(Success.getInstance(false, "#provinceCityTip", "请选择省份!"));
		}
		
		if(StringUtils.isBlank(params.get("cityId"))){
			throw new CheckException(Success.getInstance(false, "#provinceCityTip", "请选择市!"));
		}
		
		if(StringUtils.isBlank(params.get("areaId"))){
			throw new CheckException(Success.getInstance(false, "#provinceCityTip", "请选择区!"));
		}
		
		if(StringUtils.isBlank(params.get("name"))){
			throw new CheckException(Success.getInstance(false, "#nameTip", "地址不能为空!"));
		}
		if(!StringUtils.isBlank(params.get("zip")) && !RegexUtils.find(RegexUtils.ZIP, params.get("zip").toString())){
			throw new CheckException(Success.getInstance(false, "#zipTip", "邮编格式不正确!"));
		}
		if(StringUtils.isBlank(params.get("userName"))){
			throw new CheckException(Success.getInstance(false, "#userNameTip", "收货人姓名不能为空!"));
		}
		if(StringUtils.isBlank(params.get("phone"))){
			throw new CheckException(Success.getInstance(false, "#phoneTip", "手机号码不能为空!"));
		}
		if(!RegexUtils.find(RegexUtils.PHONE, params.get("phone").toString())){
			throw new CheckException(Success.getInstance(false, "#phoneTip", "手机号码不正确!"));
		}
		if(StringUtils.isBlank(params.get("email"))){
			throw new CheckException(Success.getInstance(false, "#emailTip", "邮箱不能为空!"));
		}
		if(!RegexUtils.find(RegexUtils.EMAIL, params.get("email").toString())){
			throw new CheckException(Success.getInstance(false, "#emailTip", "邮箱地址不正确!"));
		}
		if(StringUtils.isBlank(params.get("orders")) || !params.get("orders").toString().equals("1")){
			params.put("orders", 0);
		}
		params.put("remark", "");
	}
	/**
	 * 修改默认地址
	 * 
	 * @author July july_sky@foxmail.com
	 * @date 2015年10月25日下午4:05:56
	 * @param params
	 * @return
	 */
	@RequestMapping("/setAddressByDefault")
	@ResponseBody
	public Success setAddressByDefault(@RequestParam Map<String,Object> params,HttpSession session) {
		if(StringUtils.isBlank(params.get("addressIdCustomersId"))){
			return Success.getInstance(true, "500", "请选择要修改的地址");
		}
		params.put("addressIdCustomersId", Integer.valueOf(params.get("addressIdCustomersId").toString()));
		params.put("customersId", ServletUtil.getCustomerId(session));
		try {
			params.put("orders", 1);
			addressService.setAddressByDefault(params);
			return Success.getInstance(true, "200", "保存成功");
		} catch (Exception e) {
			log.error("修改默认地址异常{}",params, e);
			return Success.getInstance(false, "500", "系统异常，请稍后重试");
		}
	}
}
